package cn.uin.domain.oss.service.file;

import cn.uin.domain.auth.model.entity.HomeUserEntity;
import cn.uin.domain.auth.service.user.SecurityContextService;
import cn.uin.domain.oss.adapter.repository.IFileRepository;
import cn.uin.domain.oss.model.entity.HomeAttachmentEntity;
import cn.uin.domain.oss.model.valobj.BucketTypeEnum;
import cn.uin.domain.oss.service.MinioService;
import cn.uin.types.common.Constants;
import cn.uin.types.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @ClassName FileService
 * @Description:文件服务处理类
 * @Author: Administrator
 * @CreateDate: 2025/11/4 16:07
 * @Version: 1.0
 */
@Slf4j
@Service
public class FileService implements IFileService{

	@Resource
	private MinioService minioService;

	@Resource
	private IFileRepository iFileRepository;

	@Resource
	private SecurityContextService securityContextService;

	@Override
	public HomeAttachmentEntity uploadFile(MultipartFile file, Integer uploadType) {
		String bucketName = BucketTypeEnum.get(uploadType).getInfo();
		String fileName = UUIDUtils.generateUUID();
		try {
			minioService.uploadFile(bucketName, fileName, file);
		} catch (Exception e) {
			log.error("上传文件失败: {}", e.getMessage());
			return null;
		}

		// 获取当前用户信息
		HomeUserEntity currentUser = securityContextService.getCurrentUser();
		//保存附件信息
		String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(Constants.DOT) + 1);
		HomeAttachmentEntity homeAttachmentEntity = HomeAttachmentEntity.builder()
				.fileName(file.getOriginalFilename())
				.fileType(fileType)
				.logicPath(bucketName + "/" + fileName)
				.size(file.getSize())
				.createUserId(currentUser.getId())
				.build();
		return iFileRepository.saveHomeAttachment(homeAttachmentEntity);
	}

	@Override
	public String getFileUrl(Long fileId, Integer uploadType) {
		String bucketName = BucketTypeEnum.get(uploadType).getInfo();
		HomeAttachmentEntity homeAttachmentEntity = iFileRepository.queryById(fileId);
		try {
			String fileName = homeAttachmentEntity.getLogicPath().substring(homeAttachmentEntity.getLogicPath().lastIndexOf("/") + 1);
			return minioService.getFileUrl(bucketName, fileName);
		} catch (Exception e) {
			log.error("获取文件{}失败,错误原因:{}", homeAttachmentEntity.getFileName(), e.getMessage());
			return null;
		}
	}
}
